/* 暖言树洞 - 主要JavaScript文件 */

// ========== 全局配置 ==========
const App = {
  // 导航管理
  navigation: {
    currentPage: 'home',
    
    // 初始化导航
    init() {
      this.updateActiveNav();
      this.bindNavEvents();
    },
    
    // 更新激活状态
    updateActiveNav() {
      const navItems = document.querySelectorAll('.nav-item');
      navItems.forEach(item => {
        const page = item.getAttribute('data-page');
        if (page === this.currentPage) {
          item.classList.add('active');
        } else {
          item.classList.remove('active');
        }
      });
    },
    
    // 绑定导航事件
    bindNavEvents() {
      const navItems = document.querySelectorAll('.nav-item');
      navItems.forEach(item => {
        item.addEventListener('click', (e) => {
          e.preventDefault();
          const page = item.getAttribute('data-page');
          this.navigateTo(page);
        });
      });
    },
    
    // 导航到指定页面
    navigateTo(page) {
      // 模拟页面切换，实际项目中可以使用路由
      console.log(`导航到: ${page}`);
      this.currentPage = page;
      this.updateActiveNav();
      
      // 这里可以添加实际的页面切换逻辑
      const pageMap = {
        'home': 'home.html',
        'drift': 'drift.html',
        'profile': 'profile.html',
        'store': 'store.html'
      };
      
      if (pageMap[page]) {
        // window.location.href = pageMap[page];
      }
    }
  },
  
  // 工具函数
  utils: {
    // 格式化时间
    formatTime(timestamp) {
      const now = new Date();
      const time = new Date(timestamp);
      const diff = now - time;
      const minutes = Math.floor(diff / 60000);
      const hours = Math.floor(diff / 3600000);
      const days = Math.floor(diff / 86400000);
      
      if (minutes < 1) return '刚刚';
      if (minutes < 60) return `${minutes}分钟前`;
      if (hours < 24) return `${hours}小时前`;
      if (days < 7) return `${days}天前`;
      return time.toLocaleDateString();
    },
    
    // 生成随机ID
    generateId() {
      return 'id_' + Math.random().toString(36).substr(2, 9);
    },
    
    // 显示提示消息
    showToast(message, type = 'info') {
      const toast = document.createElement('div');
      toast.className = `toast toast-${type}`;
      toast.textContent = message;
      
      // 样式
      Object.assign(toast.style, {
        position: 'fixed',
        top: '20px',
        left: '50%',
        transform: 'translateX(-50%)',
        padding: '12px 24px',
        borderRadius: '8px',
        color: 'white',
        fontSize: '14px',
        fontWeight: '500',
        zIndex: '10000',
        animation: 'fadeInUp 0.3s ease'
      });
      
      // 根据类型设置背景色
      const colors = {
        info: '#3b82f6',
        success: '#22c55e',
        warning: '#f59e0b',
        error: '#ef4444'
      };
      toast.style.backgroundColor = colors[type] || colors.info;
      
      document.body.appendChild(toast);
      
      // 3秒后自动移除
      setTimeout(() => {
        toast.style.animation = 'fadeOut 0.3s ease';
        setTimeout(() => {
          if (toast.parentNode) {
            toast.parentNode.removeChild(toast);
          }
        }, 300);
      }, 3000);
    },
    
    // 添加CSS动画
    addAnimation(element, animationClass) {
      element.classList.add(animationClass);
      element.addEventListener('animationend', function() {
        element.classList.remove(animationClass);
      }, { once: true });
    }
  },
  
  // 数据管理 (模拟数据)
  data: {
    // 用户信息
    user: {
      id: 'user001',
      nickname: '暖心用户',
      joinDays: 15,
      currency: 128,
      stats: {
        diariesCount: 23,
        heartsReceived: 156,
        heartsGiven: 89,
        charityValue: 45
      }
    },
    
    // 示例日记数据
    diaries: [
      {
        id: 'diary001',
        title: '今天的阳光很温暖',
        content: '走在路上看到小猫咪晒太阳，突然觉得生活还是很美好的...',
        mood: '😊',
        timestamp: Date.now() - 3600000,
        aiResponse: '看到你发现生活中的小美好，我也很开心呢！阳光和小猫咪都是治愈的存在，愿你每天都能发现这样的温暖时刻~ 🐱☀️',
        heartsCount: 12,
        driftCount: 3,
        warmthScore: 4.5
      },
      {
        id: 'diary002',
        title: '有点累了',
        content: '最近工作压力好大，感觉快要撑不住了，不知道什么时候是个头...',
        mood: '😔',
        timestamp: Date.now() - 86400000,
        aiResponse: '我能感受到你的疲惫，辛苦了。每个人都有压力山大的时候，这很正常也很勇敢。记得适当休息，你已经很努力了。明天的太阳依然会升起，相信会越来越好的 💪❤️',
        heartsCount: 8,
        driftCount: 2,
        warmthScore: 4.2
      }
    ],
    
    // 漂流日记数据
    driftDiaries: [
      {
        id: 'drift001',
        content: '今天收到了一个意外的好消息，感觉整个世界都亮了起来！',
        mood: '🎉',
        timestamp: Date.now() - 1800000,
        anonymousId: '匿名用户A',
        heartsCount: 15
      },
      {
        id: 'drift002',
        content: '失恋了，但是朋友们都在安慰我，感觉还是很幸福的...',
        mood: '💔',
        timestamp: Date.now() - 7200000,
        anonymousId: '匿名用户B',
        heartsCount: 23
      }
    ],
    
    // 公益项目数据
    charityProjects: [
      {
        id: 'charity001',
        title: '山区儿童图书捐赠',
        description: '为偏远山区的孩子们送去知识的力量，让每个孩子都能享受阅读的快乐。',
        image: 'https://images.unsplash.com/photo-1497486751825-1233686d5d80?w=400',
        requiredCurrency: 50,
        participants: 156,
        progress: 78,
        organization: '希望教育基金会'
      },
      {
        id: 'charity002', 
        title: '老人院暖心陪伴',
        description: '用温暖的陪伴让孤独的老人感受到社会的关爱，传递人间真情。',
        image: 'https://images.unsplash.com/photo-1559827260-dc66d52bef19?w=400',
        requiredCurrency: 30,
        participants: 203,
        progress: 92,
        organization: '夕阳红公益协会'
      }
    ]
  },
  
  // AI回复生成器
  aiResponse: {
    // 温暖回复模板
    templates: [
      '我能感受到你的{emotion}，{comfort}。记住，你并不孤单，总有人在默默支持着你 ❤️',
      '谢谢你分享这份{emotion}，{encouragement}。愿你的每一天都充满温暖和希望 🌟',
      '听到你的故事让我{feeling}，{advice}。相信明天会更好的，加油！💪',
      '你的{emotion}让我很感动，{blessing}。保持这份美好，传递给更多人吧 ✨'
    ],
    
    // 情感词汇
    emotions: {
      '😊': { word: '快乐', comfort: '这份快乐很珍贵', encouragement: '继续保持这份美好心情', feeling: '也很开心', advice: '记得分享给身边的人', blessing: '愿这份快乐永远伴随你' },
      '😔': { word: '难过', comfort: '难过是正常的情绪', encouragement: '风雨过后总会有彩虹', feeling: '心疼你', advice: '给自己一些时间慢慢好起来', blessing: '愿温暖驱散你心中的阴霾' },
      '😤': { word: '愤怒', comfort: '生气说明你在乎', encouragement: '学会释放负面情绪很重要', feeling: '理解你的感受', advice: '深呼吸，让心情平静下来', blessing: '愿你能找到内心的平静' },
      '🎉': { word: '兴奋', comfort: '这份兴奋很有感染力', encouragement: '继续保持这份热情', feeling: '也被你的兴奋感染了', advice: '记得珍惜这美好的时刻', blessing: '愿这份兴奋带给你更多好运' }
    },
    
    // 生成AI回复
    generate(content, mood) {
      const template = this.templates[Math.floor(Math.random() * this.templates.length)];
      const emotion = this.emotions[mood] || this.emotions['😊'];
      
      return template
        .replace('{emotion}', emotion.word)
        .replace('{comfort}', emotion.comfort)
        .replace('{encouragement}', emotion.encouragement)
        .replace('{feeling}', emotion.feeling)
        .replace('{advice}', emotion.advice)
        .replace('{blessing}', emotion.blessing);
    }
  },
  
  // 表单处理
  forms: {
    // 发布日记
    submitDiary(formData) {
      const diary = {
        id: App.utils.generateId(),
        title: formData.title,
        content: formData.content,
        mood: formData.mood,
        timestamp: Date.now(),
        aiResponse: App.aiResponse.generate(formData.content, formData.mood),
        heartsCount: 0,
        driftCount: 0,
        warmthScore: 0
      };
      
      App.data.diaries.unshift(diary);
      App.utils.showToast('日记发布成功！AI猫猫正在为你写回复~', 'success');
      
      // 模拟AI回复延迟
      setTimeout(() => {
        App.utils.showToast('AI猫猫已经回复了你的日记~', 'info');
      }, 2000);
      
      return diary;
    },
    
    // 发送点评
    submitComment(diaryId, comment, warmthLevel) {
      const warmthComments = [
        '感谢你的温暖点评！',
        '你的话语很暖心~',
        '收到了满满的正能量！',
        '谢谢你的暖心鼓励！'
      ];
      
      App.utils.showToast(warmthComments[Math.floor(Math.random() * warmthComments.length)], 'success');
      
      // 增加货币奖励
      App.data.user.currency += 5;
      
      return true;
    }
  },
  
  // 初始化应用
  init() {
    console.log('暖言树洞应用初始化...');
    
    // 初始化导航
    this.navigation.init();
    
    // 绑定全局事件
    this.bindGlobalEvents();
    
    console.log('应用初始化完成!');
  },
  
  // 绑定全局事件
  bindGlobalEvents() {
    // 处理返回按钮
    document.addEventListener('click', (e) => {
      if (e.target.classList.contains('header-back') || e.target.closest('.header-back')) {
        e.preventDefault();
        history.back();
      }
    });
    
    // 处理卡片点击动效
    document.addEventListener('click', (e) => {
      if (e.target.classList.contains('card-hover') || e.target.closest('.card-hover')) {
        const card = e.target.classList.contains('card-hover') ? e.target : e.target.closest('.card-hover');
        App.utils.addAnimation(card, 'animate-fadeIn');
      }
    });
  }
};

// ========== 页面特定功能 ==========

// 发布页面功能
const PostPage = {
  moodSelected: '😊',
  
  init() {
    this.bindEvents();
    this.initMoodSelector();
    this.initCharCounter();
  },
  
  bindEvents() {
    const publishBtn = document.getElementById('publishBtn');
    const form = document.getElementById('postForm');
    
    if (publishBtn && form) {
      publishBtn.addEventListener('click', this.handlePublish.bind(this));
    }
  },
  
  initMoodSelector() {
    const moodButtons = document.querySelectorAll('.mood-btn');
    moodButtons.forEach(btn => {
      btn.addEventListener('click', (e) => {
        // 移除所有激活状态
        moodButtons.forEach(b => b.classList.remove('active'));
        // 激活当前按钮
        btn.classList.add('active');
        this.moodSelected = btn.textContent;
      });
    });
  },
  
  initCharCounter() {
    const textarea = document.getElementById('contentTextarea');
    const counter = document.getElementById('charCounter');
    
    if (textarea && counter) {
      textarea.addEventListener('input', () => {
        const count = textarea.value.length;
        counter.textContent = `${count}/500`;
        
        if (count > 500) {
          counter.style.color = 'var(--error-500)';
        } else {
          counter.style.color = 'var(--neutral-500)';
        }
      });
    }
  },
  
  handlePublish() {
    const title = document.getElementById('titleInput')?.value;
    const content = document.getElementById('contentTextarea')?.value;
    
    if (!title || !content) {
      App.utils.showToast('请填写完整的日记内容', 'warning');
      return;
    }
    
    if (content.length > 500) {
      App.utils.showToast('内容不能超过500字', 'error');
      return;
    }
    
    const formData = {
      title: title.trim(),
      content: content.trim(),
      mood: this.moodSelected
    };
    
    App.forms.submitDiary(formData);
    
    // 清空表单
    document.getElementById('titleInput').value = '';
    document.getElementById('contentTextarea').value = '';
    
    // 跳转回首页
    setTimeout(() => {
      window.location.href = 'home.html';
    }, 1500);
  }
};

// 漂流页面功能
const DriftPage = {
  currentDiary: null,
  drawCount: 0,
  maxDraws: 5,
  
  init() {
    this.bindEvents();
    this.updateDrawCounter();
  },
  
  bindEvents() {
    const drawBtn = document.getElementById('drawBtn');
    const commentBtn = document.getElementById('commentBtn');
    const likeBtn = document.getElementById('likeBtn');
    const skipBtn = document.getElementById('skipBtn');
    
    if (drawBtn) drawBtn.addEventListener('click', this.handleDraw.bind(this));
    if (commentBtn) commentBtn.addEventListener('click', this.handleComment.bind(this));
    if (likeBtn) likeBtn.addEventListener('click', this.handleLike.bind(this));
    if (skipBtn) skipBtn.addEventListener('click', this.handleSkip.bind(this));
  },
  
  handleDraw() {
    if (this.drawCount >= this.maxDraws) {
      App.utils.showToast('今日抽取次数已用完，明天再来吧~', 'info');
      return;
    }
    
    this.drawCount++;
    this.updateDrawCounter();
    
    // 随机选择一篇日记
    const randomIndex = Math.floor(Math.random() * App.data.driftDiaries.length);
    this.currentDiary = App.data.driftDiaries[randomIndex];
    
    this.displayDiary(this.currentDiary);
    App.utils.showToast('捡到一个漂流瓶！', 'success');
  },
  
  displayDiary(diary) {
    const container = document.getElementById('driftContent');
    if (!container) return;
    
    container.innerHTML = `
      <div class="card animate-fadeInUp">
        <div class="flex items-center mb-4">
          <span class="mood-emoji">${diary.mood}</span>
          <div>
            <div class="text-sm text-neutral-500">${diary.anonymousId}</div>
            <div class="text-xs text-neutral-400">${App.utils.formatTime(diary.timestamp)}</div>
          </div>
        </div>
        <p class="text-base leading-relaxed">${diary.content}</p>
        <div class="flex items-center justify-between mt-4">
          <div class="warmth-indicator">
            <i class="fas fa-heart icon-sm"></i>
            <span class="text-sm">${diary.heartsCount}</span>
          </div>
          <div class="flex gap-2">
            <button id="likeBtn" class="btn btn-sm btn-outline">
              <i class="fas fa-thumbs-up icon-sm"></i>
              默默祝福
            </button>
            <button id="commentBtn" class="btn btn-sm btn-primary">
              <i class="fas fa-comment icon-sm"></i>
              暖心点评
            </button>
            <button id="skipBtn" class="btn btn-sm btn-text">
              换一个
            </button>
          </div>
        </div>
      </div>
    `;
    
    // 重新绑定事件
    this.bindEvents();
  },
  
  updateDrawCounter() {
    const counter = document.getElementById('drawCounter');
    if (counter) {
      counter.textContent = `今日剩余 ${this.maxDraws - this.drawCount} 次`;
    }
  },
  
  handleComment() {
    // 跳转到点评页面
    window.location.href = `comment.html?diary=${this.currentDiary?.id}`;
  },
  
  handleLike() {
    if (this.currentDiary) {
      this.currentDiary.heartsCount++;
      App.data.user.currency += 2;
      App.utils.showToast('送出了温暖的祝福 +2 暖心币', 'success');
      this.displayDiary(this.currentDiary);
    }
  },
  
  handleSkip() {
    this.handleDraw();
  }
};

// DOM加载完成后初始化
document.addEventListener('DOMContentLoaded', () => {
  App.init();
  
  // 根据页面初始化特定功能
  const path = window.location.pathname;
  if (path.includes('post.html')) {
    PostPage.init();
  } else if (path.includes('drift.html')) {
    DriftPage.init();
  }
});

// 导出到全局
window.App = App;
window.PostPage = PostPage;
window.DriftPage = DriftPage;
